import React, { Fragment } from 'react';
import PropTypes from 'prop-types';
import { observer } from 'mobx-react';
import Outline, { LINE_TYPE } from '../outline';
import Dot, { DOT_TYPE } from '../dot';
import Rotate from '../rotate';
import Portal from 'components/portal';
// import Cover from '../cover';

@observer
export default class ModulePortal extends React.Component {

  static propTypes = {
    children: PropTypes.element.isRequired,
    mod: PropTypes.object.isRequired,
    active: PropTypes.bool,
    isMulti: PropTypes.bool,
  };

  static defaultProps = {
    active: false,
    isMulti: false
  };

  createPortal() {
    const { isMulti, mod: { lock, isBelongInitial }, topPosition = 0, active } = this.props;
    // console.log(isBelongInitial); // undefined at Start
    const portalProps = {
      isOpen: active,
      closeOnOutsideClick: false,
      closeOnEsc: false,
    };
    return (
      <Portal {...portalProps}>
        <Fragment>
          {this.renderOutlines(isBelongInitial, topPosition)}
          {isMulti || lock || isBelongInitial ? null : this.renderDot(isBelongInitial, topPosition)}
          {isMulti || lock || isBelongInitial ? null : this.renderRotate(isBelongInitial)}
        </Fragment>
      </Portal>
    );
  }

  renderOutlines(isBelongInitial, topPosition) {
    const directions = LINE_TYPE;
    const { mod } = this.props;

    return (
      directions.map((type, i) => {
        const _props = {
          key: i,
          mod,
          type,
          topPosition,
          style: {
            zIndex: isBelongInitial !== undefined ? 106 : null
          }
        };
        return (
          <Outline {..._props} />
        );
      })
    );
  }

  renderDot(isBelongInitial, topPosition) {
    const directions = DOT_TYPE;
    const { mod } = this.props;

    return (
      directions.map((type, i) => {
        const _props = {
          key: i,
          mod,
          type,
          topPosition,
          style: {
            zIndex: isBelongInitial !== undefined ? 106 : null
          }
        };
        return (
          <Dot {..._props} />
        );
      })
    );
  }

  renderRotate() {
    const { mod } = this.props;

    // 没有 rotate 属性，则不提供旋转
    if (mod.rotate === undefined) return null;

    return (
      <Rotate mod={mod} />
    );
  }

  render() {
    return (
      <Fragment>
        {this.createPortal()}
        {this.props.children}
      </Fragment>
    );
  }
}
